package com.ebelter.bodyfatscale.moudules.https;

import android.text.TextUtils;

import com.ebelter.bodyfatscale.moudules.https.interfaces.HttpResponse;
import com.ebelter.bodyfatscale.moudules.https.response.OriginalParametersResponse;
import com.ebelter.bodyfatscale.util.GsonUtils;
import com.ebelter.btlibrary.util.ULog;
import com.lzy.okgo.callback.AbsCallback;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;
public class MyAbsCallback<T> extends AbsCallback<T>{

    private static final String TAG = "MyAbsCallback";
    static final String  R_S_R_S = "请求成功,解析成功";
    static final String  R_S_R_F = "请求成功，解析失败";
    static final String  R_F = "请求失败";

    private Class<T> classOfT;

    public MyAbsCallback(HttpResponse<T> httpResponse, Class<T> classOfT) {
        this.httpResponse1 = httpResponse;
        this.classOfT=classOfT;

    }

    HttpResponse<T> httpResponse1;

    @Override
    public void onSuccess(T t, Call call, Response response) {
        httpResponse1.result(t != null,t != null?R_S_R_S:R_S_R_F,t);
    }

    @Override
    public void onError(Call call, Response response, Exception e) {
        super.onError(call, response, e);
        httpResponse1.result(false,R_F,null);
    }

    @Override
    public T convertSuccess(Response response) throws Exception {
        return  responseToClz(response,classOfT);
    }


    private <T> T responseToClz(Response response,Class<T> cla){
        if (response==null|| response.body()==null) return null;
        try {
            //{"resultCode":0,"resultMessage":"上传成功"}
            String json2="{\"resultCode\":0,\"resultMessage\":\"上传成功\"}";
            ULog.i(TAG,"尝试解析："+json2);
            OriginalParametersResponse response2 = GsonUtils.getInstance().fromJson(json2,OriginalParametersResponse.class);
            ULog.i(TAG,"尝试解析出："+response2);

            if(cla==OriginalParametersResponse.class){
                ULog.i(TAG,"---.class文件是一样的---");
            }


            String json=response.body().string();

            if(TextUtils.equals(json2,json)){
                ULog.i(TAG,"两个json是一样的");
            }

            ULog.i(TAG,"classOfT.getSimpleName:"+cla.getSimpleName()+"---json---"+json);
            return GsonUtils.getInstance().fromJson(json,cla);
        } catch (IOException e) {
            e.printStackTrace();
            ULog.i(TAG,"------json解析出错");
        }
        return null;
    }


}
